package top.codingfly.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.codingfly.model.resp.common.Response;
import top.codingfly.service.IRedisLockService;

import javax.annotation.Resource;

@RestController
@RequestMapping("/redisLock")
public class RedisLockController {

    @Resource
    private IRedisLockService redisLockService;
    private static final String timeoutOrderRedisKey = "pre-authority:timeoutOrder:scheduled-task";
    private static final Logger logger = LoggerFactory.getLogger(RedisLockController.class);

    @GetMapping("/testLock")
    public Response<Boolean> testLock() {
        try {
            boolean getLock = redisLockService.tryLock(timeoutOrderRedisKey, 100L, 60 * 60 * 1000L);
            if (getLock == false) {
                logger.info("获取不到超时订单定时任务的分布式处理锁，不往下执行");
                return Response.success(false);
            } else {
                Thread.sleep(1333L);
                return Response.success(true);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.success(false);
        } finally {
            redisLockService.releaseLock(timeoutOrderRedisKey);
        }
    }

}